<?php

namespace control;

//管理员后台 - 用户管理
use http\Exception;

class userClass extends adIndexClass
{
    private const page = 'user'; # 权限
    private const table = 'user'; # 数据表
    private const title = '用户信息';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'name'          => [
                        'name'  => L('setting.table.xing_ming'),
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'tel'  => [
                        'name'  => L('setting.table.shou_ji_hao'),
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'userName'         => [
                        'name'  => L('setting.table.yong_hu_ming'),
                        'width' => 300,
                    ],
                    'role'          => [
                        'name'  => L('setting.table.role'),
                        'width' => 400,
                    ],
                    'state'          => [
                        'name'  => L('setting.table.zhuang_tai'),
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('setting.table.xing_ming') => text(array("name" => "name")),
                    L('setting.table.shou_ji_hao')   => text(array("name" => "tel")),
                    L('setting.table.yong_hu_ming') => text(array("name" => "userName")),
                ],
                [
                    L('setting.table.zhuang_tai') => select(["name" => "state", 'option' => ['启用', '停用']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*成本表列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = '';
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('".self::page."','editPage')\">新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "state")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'changeState', state: '启用' })\">启用</span>\n";
        }
        if ($this->power(self::page, "state")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'changeState', state: '停用'})\">停用</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .=
                importTemplateClass::importTemplateButton(self::page) .
                $this->upButton(array("title" => '导入', "fun" => "importData"));
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*成本表列表-查询结果*/
    public function homeSearch()
    {
        $where = ' 1=1 ';
        $equal = [
            'state' => $this->post('state'),
        ];
        $like  = [
            'name'     => $this->post('name'),
            'tel'      => $this->post('tel'),
            'userName' => $this->post('userName'),
        ];
        $where .= search([
            "="    => $equal,
            "like" => $like,
        ]);

        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $page                        = $this->page([
            "table" => self::table,
            "where" => $where,
            "order" => $orderBy['orderBy'],

        ]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "id")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail";
        foreach ($page['array'] as $array) {
            $dominate = [
                "box"    => [
                    "name"  => "id",
                    "value" => $array['uid'],
                ],
                "detail" => [
                    "title" => L('setting.table.yhxq'),
                    "click" => "newIframe('" . L('setting.table.yhxq') . "','" . $url . "&id=" . $array['uid'] . "')",
                ],
            ];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'role':
                        $row[] = self::getRoleName($array['role']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = '';
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '您没有编辑权限';
        } else {
            $title  = ["*员工编号", "员工姓名", '*用户名', '*角色名称(多个用英文逗号隔开)', '*初始密码', '备注'];
            $data[] = ['YM202311070001', '蒋丽', 'jiangli', '行政主管,销售员', '123456', '样例数据，导入时请删除本条数据'];
            $text   = $this->control['name'] . "下载了用户导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . '.xlsx');
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /*数据导入分析*/
    public function importData()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '您没有编辑权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x    = 0;
            $text = '';
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $cell  = formSubArray($row);
                    $staff = query("staff", " orderNo = '$cell[0]' ", "stid,tel,name");
                    if (empty($staff['stid'])) {
                        $text .= "员工编号【{$cell[0]}】在系统中不存在";
                        continue;
                    }
                    $role     = [];
                    $roleName = explode(',', $cell[3]);
                    foreach ((array)$roleName as $item) {
                        $arr = query("role", " name = '$item' ", "id");
                        if ($arr['id']) $role[] = $arr['id'];
                    }
                    $field      = array(
                        'stid'     => $staff['stid'],
                        'name'     => $staff['name'],
                        'userName' => $cell[2],
                        'role'     => count($role) > 0 ? json_encode($role, 320) : '',
                        'tel'      => $staff['tel'],
                        'password' => $cell[4],
                        'text'     => $cell[5],
                    );
                    $annotation = [
                        'userName' => "用户名",
                        'role'     => "角色名称系统中未找到，",
                        'password' => L('setting.table.mi_ma'),
                        'text'     => L('setting.table.bei_zhu'),
                    ];
                    $rules      = [
                        'userName' => 'required',
                        'role'     => 'required',
                        'password' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt     = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    $total  = 0;
                    // 非无限用户 设定用户数
                    $users = (int)para('userNumberLimit');
                    if ($users != -1) {
                        // 已有用户数
                        $total = static::total(['table' => 'user', 'where' => " 1=1 "]);
                    }
                    if ($result === false) {
                        $text .= str_replace(['{{i}}'], [$i], L('resource.importData.row')) . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } elseif ($users != -1 && $total >= $users) {
                        $text .= str_replace(['{{num}}'], [$users], L('setting.table.user_new_warn'));
                    } elseif (sqlNum(self::table, " (userName = '{$field['userName']}' OR tel = '{$field['tel']}')  ") > 0) {
                        $text .= str_replace(['{{name}}', '{{tel}}'], [$field['userName'], $field['tel']], L('setting.table.user_repeat'));
                    } else {
                        // 密码不为空
                        $field['password'] = md5s($field['password']);
                        $userNo = codeTemplateClass::generateCode('user', [
                            'prefix' => 'UID' . date('Ymd'),
                            'table'  => 'user',
                            'field'  => 'userNo',
                            'where'  => '',
                        ], $field);
                        $field  = array_merge($field, [
                            'uid'      => self::getId(),
                            'userNo'   => $userNo,
                            'operator' => $this->control['stid'],
                            'state'    => '启用',
                            'time'     => $this->time,
                        ]);
                        $warn   = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "用户【{$cell[2]}】导入成功<br>";
                        } else {
                            $text .= "用户【{$cell[2]}】导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('resource.importData.log')) . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $warn             = str_replace(['{{x}}'], [$x], L('resource.importData.warn'));
            $_SESSION['warn'] = $warn;
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '您没有编辑权限';
        } else {
            $data   = [];
            $sql    = $_SESSION[self::page]['sql'];
            $title  = ['员工编号', '员工姓名', '用户名', '角色名称（多个角色逗号隔开）', '备注'];
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $staff  = query("staff", " stid = '$array[stid]' ", "orderNo");
                    $data[] = [
                        $staff['orderNo'], $array['name'], $array['userName'], self::getRoleName($array['role']), $array['text']
                    ];
                }
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 获取角色名称
     *
     * @param string $ids
     */
    public static function getRoleName($ids)
    {
        $roleName  = '';
        $roleArray = (array)json_decode($ids, true);
        foreach ($roleArray as $rid) {
            $role     = query('role', " id = '$rid' ");
            $roleName .= isset($role['name']) ? ($role['name'] . ';') : '';
        }
        return $roleName;
    }


    /**
     * 新建
     *
     * @return void
     */
    public function detail()
    {
        $info = query(self::table, " uid = '" . $this->get('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $html = L('setting.table.nmzckzx');
        } elseif (!$this->get('id')) {
            $html = L('setting.table.id_empty');
        } elseif (!$info['uid']) {
            $html = L('setting.table.wzdcxx');
        } else {
            $data = [
                "id" => $info['uid'],
            ];
            //按钮
            $button = [];
            if ($this->power(self::page, "edit")) {
                $button[] = [
                    "name" => '清零登录错误次数',
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'clearError', "id" => $info['uid']],
                ];
                $button[] = [
                    "name" => '重置密码',
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'resetPass', "id" => $info['uid']],
                ];
                $button[] = [
                    "name" => L('setting.table.shan_chu'),
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'del', "id" => $info['uid']],
                ];
                $opt      = ($info['state']) == '停用' ? '启用' : '停用';
                $button[] = [
                    "name" => $opt,
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'changeState', "id" => $info['uid'], 'state' => $opt],
                ];
                $button[] = [
                    "name"  => L('setting.table.edit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "editPage",
                    "post" => ["id" => $info['uid']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                L('setting.table.ji_ben_xin_xi')  => [
                    [
                        L('setting.table.xing_ming')    => $info['name'],
                        L('setting.table.shou_ji_hao')  => $info['tel'],
                        L('setting.table.yong_hu_ming') => $info['userName'],
                        "角色" => self::getRoleName($info['role']),
                    ],
                    [
                        L('setting.table.bei_zhu') => pre($info['text']),
                    ],
                ],
                L('setting.table.xi_tong_xin_xi') => [
                    [
                        L('setting.table.yhbh')            => $info['userNo'],
                        L('setting.table.chuang_jian_ren') => self::findStaff($info['stid'], 'name'),
                        L('setting.table.cjsj')            => $info['time'],
                        L('setting.table.gxsj')       => $info['updateTime'],
                    ],
                    [
                        L('setting.table.zhuang_tai') => $info['state'],
                        '登录密码错误次数' => $info['loginError'],
                    ],
                ],
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    public function editPage()
    {
        $id   = $this->post('id') ?: self::getId();
        $info = query(self::table, " uid = '" . $id . "' ");
        if ($this->post('staffId')) {
            $staff        = query('staff', "stid = '" . $this->post('staffId') . "'");
            $info['tel']  = $staff['tel'];
            $info['name'] = $staff['name'];
        }
        // 角色
        $roleOption = [];
        $role       = find(['table' => 'role', 'where' => ' 1=1 ']);
        foreach ($role['array'] as $val) {
            $roleOption[$val['id']] = $val['name'];
        }
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "姓名：" => selectMultiple([
                            "name"     => "stid",
                            "title"    => L('setting.table.yuan_gong'),
                            'value'    => $info['stid'] ?: $this->get('staffId'),
                            'class'    => 'textLong',
                            'sqlId'    => 'stid',
                            'sqlField' => 'name',
                            'table'    => 'staff',
                            'where'    => "state !='离职' and workFlow ='已复核' order by orderNo",
                            'change'   => 'getUserTel',
                        ])
                        . hidden(['name' => 'name', 'value' => $info['name']]),
                    "手机号：" => '<span id="editPage-tel">' . $info['tel'] . '</span>' . hidden(['name' => 'tel', 'value' => $info['tel']]),
                ],
                [
                    must . "用户名：" => text(["name" => "userName", "value" => $info['userName']]),
                ],
                /*[
                    "密码：" => hidden(['name' => 'password', 'value' => '']) . (!empty($info['uid']) ? "<span id='pwd'>***********</span><span class='spanButton' id='copy-btn' data-pas>重置并复制</span>" : para('staffPas') . ' (初始密码)'),
                ],*/
                [
                    must . "角色：" => "<div class='roleDiv'>".checkbox(["name" => "role", 'class' => 'textLong', 'value' => $roleOption, "checked" => json_decode($info['role'], true)])."</div>",
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                        . hidden(['name' => 'id', 'value' => $info['uid'] ?: $id]),
                ],
            ],
        ]);
        $html .= <<<EOT
        <script>
        function getUserTel(obj) {
            let id = $(obj).find("option:selected").val()
            if(id.length>0){
                $('[name="name"]').val($(obj).find("option:selected").text())
                $.post(root+'control/adIndex.html?cla=user&fun=getUserTel', {id: id}, function(res){
                    if(res.warn === 1){
                        $('[name="tel"]').val(res.data.tel)
                         $('[name="userName"]').val(res.data.name)
                        $('#editPage-tel').html(res.data.tel)
                    }
                },'json')
            }
        }
        </script>
EOT.$this->resetPwdJs();
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 450, "html" => $html));
    }

    /**
     * Desc : 重置密码js
     * User : you name
     * Date : 2024-01-20 11:52
     * @return string
     */
    public function resetPwdJs()
    {
        $mmfzcg = L('setting.table.mmfzcg');
        $mmfzsbqsdfz = L('setting.table.mmfzsbqsdfz');
        return <<<EOT
        <script src='{$this->root}static/javascript/clipboard.min.js'></script>
        <script>
        var pageCtrl = {
            getPass: function(ele) {
                $.ajax({
                    url: root + 'control/adIndex.html?cla=user&fun=resetPwd',
                    type: 'post',
                    data: {
                        id : $('[name="id"]').val()
                    },
                    dataType: 'json',
                    async: false,
                    success: function(res) {
                        if(res.code == 1){
                            ele.val(res.data)
                        }else{
                            msg(res.msg, 'error')
                        }
                    }
                });
            },
            clip: function() {
                let that = this,
                clipboard = new ClipboardJS('#copy-btn', {
                    text: function(el) {
                        let obj = $("[name='password']")
                        that.getPass(obj); //ajax请求并设置要复制的字符串
                        return obj.val()
                    }
                });
                clipboard.on('success', function(e) {
                    console.log(e)
                    msg('{$mmfzcg}')
                    e.clearSelection();
                });
                clipboard.on('error', function(e) {
                    console.log(e)
                    msg('{$mmfzsbqsdfz}', 'error')
                    e.clearSelection();
                });
            },

            init: function() {
                this.clip();
            }
        };
        $(function() {
            pageCtrl.init();
        });
        </script>
EOT;
    }
    public function randomPassword($length = 15) {
        // 生成包含字母大小写、数字和字符的所有可能字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
        // 初始化密码变量
        $password = '';

        // 生成随机密码
        for ($i = 0; $i < $length; $i++) {
            // 从字符集中随机选择一个字符
            $password .= $chars[rand(0, strlen($chars) - 1)];
        }

        return $password;
    }
    public function resetPwd()
    {
        $id   = $this->post('id') ? $this->post('id') : '';
        $data = [
            'code' => 0,
        ];
        if (!$id) {
            $data['warn'] = L('setting.table.csbnwk');
        } elseif (!$this->power(self::page, "edit")) {
            $data['warn'] = "你没有编辑" . self::title . "的权限";
        } else {
            //$password     = para('staffPas');
            $password     = $this->randomPassword();
            /*$data['warn'] = static::update([
                'table' => self::table,
                'field' => [
                    'password'   => md5s($password),
                    'loginError' => 0,
                ],
                'where' => " uid = '$id' ",
            ]);
            if (in_array($data['warn'], ['更新成功', '新增成功'])) {
                $data = [
                    'msg'  => L('setting.table.mmzzcg'),
                    'data' => $password,
                    'code' => 1,
                ];
            }*/
            $data = [
                'msg'  => L('setting.table.mmzzcg'),
                'data' => $password,
                'code' => 1,
            ];
        }
        return json_encode($data, 320);
    }

    public function getUserTel()
    {
        $id   = $this->post('id') ? $this->post('id') : '';
        $json = [];
        if (!$id) {
            $json['warn'] = L('setting.table.csbnwk');
        } else {
            $json['warn'] = 1;
            $staff        = query('staff', "stid = '$id'");
            $json['data'] = [
                'tel'  => $staff['tel'],
                'name' => $staff['name']
            ];
        }
        return json_encode($json, 320);
    }

    /*成本表基本资料新增或修改-异步处理*/
    public function editPageEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            'stid'     => $this->post('stid'),
            'name'     => $this->post('name'),
            'userName' => $this->post('userName'),
            'role'     => $this->post('role') ? json_encode($this->post('role'), 320) : '',
            'tel'      => $this->post('tel'),
            'text'     => $this->post('text'),
        ];
        $annotation = [
            'stid'     => L('setting.table.staffId'),
            'name'     => L('setting.table.xing_ming'),
            'userName' => L('setting.table.yong_hu_ming'),
            'role'     => L('setting.table.role'),
            'tel'      => L('setting.table.shou_ji_hao'),
            'password' => L('setting.table.mi_ma'),
            'text'     => L('setting.table.bei_zhu'),
        ];
        $rules      = [
            'stid'     => 'required',
            'name'     => 'required',
            'userName' => 'required',
            'role'     => 'required',
            'tel'      => 'required|unsigned_int',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " uid = '$id' ";
        $info  = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('setting.table.user_edit_permission');
        } else {
            // 非无限用户 设定用户数
            $users = (int)para('userNumberLimit');
            if ($users != -1) {
                // 已有用户数
                $total = static::total(['table' => 'user', 'where' => " 1=1 "]);
                if ($total >= $users) {
                    $json['warn'] = str_replace(['{{num}}'], [$users], L('setting.table.user_new_warn'));
                    goto resp;
                }
            }
            if (sqlNum(self::table, " (userName = '{$field['userName']}' OR tel = '{$field['tel']}') AND uid <> '$id'   ") > 0) {
                $json['warn'] = str_replace(['{{name}}', '{{tel}}'], [$field['userName'], $field['tel']], L('setting.table.user_repeat'));
                goto resp;
            }

            // 密码不为空
            if ($this->post('password')) {
                $field['password'] = md5s($this->post('password'));
            }
            if (!$info['uid']) {
                $userNo       = codeTemplateClass::generateCode('user', [
                    'prefix' => 'UID' . date('Ymd'),
                    'table'  => 'user',
                    'field'  => 'userNo',
                    'where'  => '',
                ], $field);
                $field        = array_merge($field, [
                    'uid'      => $id,
                    'userNo'   => $userNo,
                    'password' => md5s(para('staffPas')),
                    'operator' => $this->control['stid'],
                    'state'    => '启用',
                    'time'     => $this->time,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['name'], $id], L('setting.table.user_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act    = $this->post('act') ?? '';
        $pwd    = $word = false; // 需要密码
        $append = [];
        switch ($act) {
            case 'changeState':
                $act      = 'state';
                $msg      = self::title . L('setting.table.xgzt');
                $title    = self::table . 'Change';
                $function = 'changeState';
                $form     = 'userOperateForm, listForm';
                if ($this->post('state')) {
                    $append = [
                        0 => hidden(['name' => 'state', 'value' => $this->post('state')]),
                    ];
                }
                $power = '';
                break;
            case 'clearError':
                $act      = 'edit';
                $msg      = '清零登录错误次';
                $title    = '清零登录错误次后，用户可重新登录。';
                $function = 'clearErrorEdit';
                $form     = 'userOperateForm, listForm';
                $word     = true;
                $power = '';
                break;
            case 'resetPass':
                $act      = 'edit';
                $msg      = "重置登录密码";
                $title    = "";
                $function = 'resetPassEdit';
                $form     = 'userOperateForm, listForm';
                $append = [
                    "密码：" => text(['name' => 'password', 'class' => 'width150', 'value' => '']) . "<span class='spanButton' id='copy-btn' data-pas>重置并复制</span>".$this->resetPwdJs(),
                ];
                $word     = true;
                $power = '';
                break;
            default:
                $act      = 'del';
                $msg      = L('setting.table.user_del_title');
                $title    = self::table . 'Delete';
                $function = 'isDelete';
                $form     = 'userOperateForm, listForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'append'   => $append,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 修改状态
     */
    public function changeState()
    {
        $array = $this->post('listId') ?? $this->post('id');
        $state = $this->post('state');
        $act   = 'state';
        $json  = [];
        if (!$this->power(self::page, $act)) {
            $json['warn'] = L('setting.table.nmzczxdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('setting.table.nytjldmzxzn');
        } else {
            $text  = '';
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            // 修改field
            $fieldKey = 'state';
            foreach ($array as $id) {
                $where = " uid = '$id' ";
                $info  = query(self::table, $where);
                if ($info['uid']) {
                    if ($info['state'] == $state) {
                        continue;
                    }
                    $fieldVlaue = ($info['state'] == '启用') ? '停用' : '启用';
                    // 修改状态
                    static::update([
                        "table" => self::table,
                        'field' => [
                            $fieldKey => $fieldVlaue,
                        ],
                        "where" => $where,
                    ]);
                    //添加记录
                    $text .= str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $info['name'], $info['uid']], L('setting.table.user_change_text')) . "<br>";
                    $x++;
                }
            }
            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('setting.table.user_change_log'));
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        resp:
        return json_encode($json, 320);
    }
    /**
     * 清零登录错误次数
     */
    public function clearErrorEdit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        $act   = 'edit';
        $json  = [];
        if (!$this->power(self::page, $act)) {
            $json['warn'] = L('setting.table.nmzczxdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('setting.table.nytjldmzxzn');
        } else {
            $text  = '';
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $where = " uid = '$id' ";
                $info  = query(self::table, $where);
                if ($info['uid']) {
                    // 修改状态
                    static::update([
                        "table" => self::table,
                        'field' => [
                            'loginError' => 0,
                        ],
                        "where" => $where,
                    ]);
                    //添加记录
                    $text .= "{$this->control['name']}清零登录错误次数，用户【{$info['name']}】,ID【{$info['uid']}】<br>";
                    $x++;
                }
            }
            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "操作成功";
            $json['warn']     = 2;
        }
        resp:
        return json_encode($json, 320);
    }
    /**
     * 重置登录密码
     */
    public function resetPassEdit()
    {
        $id = $this->post('id');
        $where = " uid = '$id' ";
        $info  = query(self::table, $where);
        $act   = 'edit';
        $json  = [];
        if (!$this->power(self::page, $act)) {
            $json['warn'] = L('setting.table.nmzczxdzx');
        } elseif (empty($info['uid'])) {
            $json['warn'] = '用户不存在';
        } elseif (empty($this->post('password'))) {
            $json['warn'] = '登录密码不能为空';
        } else {
            // 修改状态
            static::update([
                "table" => self::table,
                'field' => [
                    'password' => md5s($this->post('password')),
                    'loginError' => 0,
                ],
                "where" => $where,
            ]);
            $text = "{$this->control['name']}重置登录密码，用户【{$info['name']}】,ID【{$info['uid']}】";
            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "操作成功";
            $json['warn']     = 2;
        }
        resp:
        return json_encode($json, 320);
    }


    // 确认删除信息
    public function isDelete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('setting.table.user_del_permission');
        } elseif (empty($array)) {
            $json['warn'] = L('setting.table.nytjldmzxzn');
        } else {
            $text  = '';
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey   = 'state';
            $fieldVlaue = '启用';

            foreach ($array as $id) {
                $where = " uid = '$id' ";
                $info  = query(self::table, $where);
                if ($info['uid']) {
                    if ($info[$fieldKey] == $fieldVlaue) {
                        $text .= str_replace(['{{name}}'], [$info['name']], L('setting.table.user_del_warn_one')) . "<br>";
                        continue;
                    }
                    if ($info['isDel']) {
                        $text .= str_replace(['{{name}}'], [$info['name']], L('setting.table.user_del_warn_two')) . "<br>";
                        continue;
                    }
                    // 删除表
                    delete([
                        "table" => self::table,
                        "where" => $where,
                    ]);
                    //添加记录
                    $text .= str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $info['name'], $id], L('setting.table.user_del_text')) . "<br>";
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('setting.table.user_del_msg'));
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }

        resp:
        return json_encode($json, 320);
    }
}
